package team.first.movieapiv2.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.mongodb.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import team.first.movieapiv2.domain.Movie;
import team.first.movieapiv2.dto.RequestMovie;
import team.first.movieapiv2.util.MongoDBUtil;
import team.first.movieapiv2.vo.ApiResponse;
import team.first.movieapiv2.vo.ApiResponsePaging;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapibootv2.controller
 * @Date: 2021/11/19 7:39
 * @Description：
 */
@RestController
public class MovieController {
    DBCollection collection = MongoDBUtil.getCollection("movie");

    /**
     * 1.2 获取指定编号的电影信息
     * 接口地址：GET /api/v2/movie/{movieId}
     */
    @ApiOperation("1.2 GET: 获取指定编号的电影信息")
    @GetMapping("/api/v2/movie/{movieId}")
    public ApiResponse<Movie> getMovieById(@PathVariable("movieId") Integer movieId) {
        ApiResponse<Movie> apiResponse = new ApiResponse<>();

        // 建立查询条件
        BasicDBObject filter_dbobject = new BasicDBObject();
        filter_dbobject.put("id", movieId);

        // 条件查询
        DBCursor cursor = collection.find(filter_dbobject).sort(new BasicDBObject("id", 1));

        // 将结果转为集合
        List<DBObject> dbObjectList = cursor.toArray();
        // 属性考呗
        List<Movie> movieList = BeanUtil.copyToList(dbObjectList, Movie.class);

        // 根据编号查询结果只有一条
        apiResponse.setCode(200).setSuccess(true).setMessage("请求成功").setData(movieList.size() > 0 ? movieList.get(0) : null);
        return apiResponse;
    }

    /**
     * 2.3 根据条件分页获取指定的电影列表
     * 接口地址:POST /api/v2/movies
     */
    @PostMapping("/api/v2/movies")
    @ApiOperation("1.3 POST: 根据条件分页获取指定的电影列表")
    public ApiResponsePaging<List<Movie>> movies(RequestMovie requestMovie) {
        ApiResponsePaging<List<Movie>> apiResponsePaging = new ApiResponsePaging<>();

        // 建立查询条件
        BasicDBObject filter_dbobject = new BasicDBObject();
        if (requestMovie.getOriginalTitle() != null) {
            filter_dbobject.put("originalTitle", Pattern.compile("^.*" + requestMovie.getOriginalTitle() + ".*$", Pattern.CASE_INSENSITIVE));
        }
        if (requestMovie.getChineseTitle() != null) {
            filter_dbobject.put("chineseTitle", Pattern.compile("^.*" + requestMovie.getChineseTitle() + ".*$", Pattern.CASE_INSENSITIVE));
        }
        List<BasicDBObject> yearConditions = new ArrayList<>();
        if (requestMovie.getStartYear() != null) {
            BasicDBObject basicDBObject = new BasicDBObject();
            basicDBObject.append("year", new BasicDBObject("$gte", requestMovie.getStartYear()));
            yearConditions.add(basicDBObject);
        }
        if (requestMovie.getEndYear() != null) {
            BasicDBObject basicDBObject = new BasicDBObject();
            filter_dbobject.append("year", new BasicDBObject("$lte", requestMovie.getEndYear()));
            yearConditions.add(basicDBObject);
        }
        if (yearConditions.size() > 0) {
            filter_dbobject.put("$and", yearConditions);
        }
        if (requestMovie.getLanguage() != null) {
            filter_dbobject.put("language", Pattern.compile("^.*" + requestMovie.getLanguage() + ".*$", Pattern.CASE_INSENSITIVE));
        }
        if (requestMovie.getGenreIds() != null) {
            BasicDBList basicDBList = new BasicDBList();
            for (Integer genreId : requestMovie.getGenreIds()) {
                basicDBList.add(genreId);
            }
            filter_dbobject.put("genres.id", new BasicDBObject("$in", basicDBList));
        }
        if (requestMovie.getRegion() != null) {
            filter_dbobject.put("region", Pattern.compile("^.*" + requestMovie.getRegion() + ".*$", Pattern.CASE_INSENSITIVE));
        }
        //下面执行查询，设置limit,只要10条数据,排序(类mysql orderby) 再建一个BasicDBObject即可，－1表示倒序
        DBCursor cursor = collection.find(filter_dbobject);
        int totalRow = cursor.count();
        if (requestMovie.getPagerSize() != null) {
            cursor.limit(requestMovie.getPagerSize());
        }
        int offset = 0;
        if (requestMovie.getPageNumber() != null) {
            offset = (requestMovie.getPageNumber() - 1) * requestMovie.getPagerSize();
        }
        if (requestMovie.getOffset() != null) {
            offset += requestMovie.getOffset();
        }
        cursor.skip(offset);
        if (requestMovie.getOrderField() != null) {
            // 根据排序规则排序，默认升序
            if (requestMovie.getOrderDirection() != null) {
                cursor.sort(new BasicDBObject(requestMovie.getOrderField(), "ASC".equalsIgnoreCase(requestMovie.getOrderDirection()) ? 1 : -1));
            } else {
                cursor.sort(new BasicDBObject(requestMovie.getOrderField(), 1));
            }
        }
        List<DBObject> dbObjects = cursor.toArray();
        List<Movie> movieList = BeanUtil.copyToList(dbObjects, Movie.class);

        apiResponsePaging.setCode(200).setSuccess(true).setMessage("请求成功").setData(movieList).setTotalRow(totalRow);

        if (requestMovie.getPagerSize() != null) {
            apiResponsePaging.setPageSize(requestMovie.getPagerSize())
                    .setTotalPage(Convert.toInt(Math.ceil((double) totalRow / requestMovie.getPagerSize())));
        }
        if (requestMovie.getPageNumber() != null) {
            apiResponsePaging.setPageNumber(requestMovie.getPageNumber());
        }

        return apiResponsePaging;
    }
}
